{extend name="layout/main" /}

{block name="style"}
<style>
    .form-container {
        max-width: 600px;
        margin: 0 auto;
    }
    
    .form-card {
        background: white;
        border-radius: 8px;
        box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        overflow: hidden;
    }
    
    .form-header {
        background: #f8f9fa;
        padding: 20px;
        border-bottom: 1px solid #e9ecef;
    }
    
    .form-title {
        margin: 0;
        font-size: 18px;
        font-weight: 600;
        color: #2c3e50;
    }
    
    .form-body {
        padding: 30px;
    }
    
    .form-group {
        margin-bottom: 20px;
    }
    
    .form-label {
        display: block;
        margin-bottom: 8px;
        font-weight: 500;
        color: #333;
    }
    
    .form-label.required::after {
        content: " *";
        color: #e74c3c;
    }
    
    .form-control {
        width: 100%;
        padding: 12px 16px;
        border: 1px solid #ddd;
        border-radius: 6px;
        font-size: 14px;
        transition: border-color 0.3s, box-shadow 0.3s;
    }
    
    .form-control:focus {
        outline: none;
        border-color: #3498db;
        box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.1);
    }
    
    .form-control.error {
        border-color: #e74c3c;
    }
    
    .form-help {
        font-size: 12px;
        color: #666;
        margin-top: 5px;
    }
    
    .form-error {
        font-size: 12px;
        color: #e74c3c;
        margin-top: 5px;
        display: none;
    }
    
    .form-actions {
        display: flex;
        gap: 10px;
        justify-content: flex-end;
        padding-top: 20px;
        border-top: 1px solid #f0f0f0;
    }
    
    .checkbox-group {
        display: flex;
        align-items: center;
        gap: 8px;
    }
    
    .checkbox-group input[type="checkbox"] {
        width: auto;
    }
    
    .loading {
        opacity: 0.6;
        pointer-events: none;
    }
    
    @media (max-width: 768px) {
        .form-container {
            margin: 0 10px;
        }
        
        .form-body {
            padding: 20px;
        }
        
        .form-actions {
            flex-direction: column;
        }
    }
</style>
{/block}

{block name="breadcrumb"}
<span class="breadcrumb-item">首页</span>
<span class="breadcrumb-item"><a href="/admin/account">账号管理</a></span>
<span class="breadcrumb-item active">添加管理员</span>
{/block}

{block name="content"}
<div class="form-container">
    <div class="form-card">
        <div class="form-header">
            <h3 class="form-title">添加管理员</h3>
        </div>
        
        <div class="form-body">
            <form id="addAdminForm">
                <div class="form-group">
                    <label class="form-label required">用户名</label>
                    <input type="text" name="username" class="form-control" placeholder="请输入用户名" maxlength="50">
                    <div class="form-help">用户名用于登录，只能包含字母、数字和下划线</div>
                    <div class="form-error" id="username-error"></div>
                </div>
                
                <div class="form-group">
                    <label class="form-label required">密码</label>
                    <input type="password" name="password" class="form-control" placeholder="请输入密码" maxlength="100">
                    <div class="form-help">密码长度至少6位，建议包含字母、数字和特殊字符</div>
                    <div class="form-error" id="password-error"></div>
                </div>
                
                <div class="form-group">
                    <label class="form-label required">确认密码</label>
                    <input type="password" name="password_confirm" class="form-control" placeholder="请再次输入密码" maxlength="100">
                    <div class="form-error" id="password_confirm-error"></div>
                </div>
                
                <div class="form-group">
                    <label class="form-label">昵称</label>
                    <input type="text" name="nickname" class="form-control" placeholder="请输入昵称（可选）" maxlength="50">
                    <div class="form-help">昵称用于显示，如不填写则使用用户名</div>
                </div>
                
                <div class="form-group">
                    <label class="form-label">邮箱</label>
                    <input type="email" name="email" class="form-control" placeholder="请输入邮箱（可选）" maxlength="100">
                    <div class="form-error" id="email-error"></div>
                </div>
                
                <div class="form-group">
                    <label class="form-label">权限级别</label>
                    <select name="role" class="form-control">
                        <option value="admin">普通管理员</option>
                        {if isset($admin_user.role) && $admin_user.role == 'super_admin'}
                        <option value="super_admin">超级管理员</option>
                        {/if}
                    </select>
                    <div class="form-help">超级管理员拥有所有权限，只有超级管理员才能创建超级管理员</div>
                </div>
                
                <div class="form-group">
                    <div class="checkbox-group">
                        <input type="checkbox" name="status" id="status" value="1" checked>
                        <label for="status" class="form-label">启用账号</label>
                    </div>
                    <div class="form-help">取消勾选将创建禁用状态的账号</div>
                </div>
                
                <div class="form-actions">
                    <a href="/admin/account" class="btn" style="background: #95a5a6;">取消</a>
                    <button type="submit" class="btn btn-success">添加管理员</button>
                </div>
            </form>
        </div>
    </div>
</div>
{/block}

{block name="script"}
    document.getElementById('addAdminForm').addEventListener('submit', function(e) {
        e.preventDefault();
        
        // 清除之前的错误信息
        clearErrors();
        
        // 获取表单数据
        const formData = new FormData(this);
        const data = {};
        for (let [key, value] of formData.entries()) {
            data[key] = value;
        }
        
        // 前端验证
        if (!validateForm(data)) {
            return;
        }
        
        // 显示加载状态
        const submitBtn = this.querySelector('button[type="submit"]');
        const originalText = submitBtn.textContent;
        submitBtn.textContent = '添加中...';
        submitBtn.disabled = true;
        this.classList.add('loading');
        
        // 提交数据
        fetch('/admin/account/add', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: new URLSearchParams(data)
        })
        .then(response => response.json())
        .then(result => {
            if (result.code === 1) {
                alert('添加成功！');
                window.location.href = result.url || '/admin/account';
            } else {
                alert('添加失败：' + result.msg);
                
                // 显示服务器端验证错误
                if (result.errors) {
                    showErrors(result.errors);
                }
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('网络错误，请重试');
        })
        .finally(() => {
            // 恢复按钮状态
            submitBtn.textContent = originalText;
            submitBtn.disabled = false;
            this.classList.remove('loading');
        });
    });
    
    // 前端表单验证
    function validateForm(data) {
        let isValid = true;
        
        // 验证用户名
        if (!data.username || data.username.trim().length < 3) {
            showError('username', '用户名至少3个字符');
            isValid = false;
        } else if (!/^[a-zA-Z0-9_]+$/.test(data.username)) {
            showError('username', '用户名只能包含字母、数字和下划线');
            isValid = false;
        }
        
        // 验证密码
        if (!data.password || data.password.length < 6) {
            showError('password', '密码至少6个字符');
            isValid = false;
        }
        
        // 验证确认密码
        if (data.password !== data.password_confirm) {
            showError('password_confirm', '两次输入的密码不一致');
            isValid = false;
        }
        
        // 验证邮箱格式
        if (data.email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(data.email)) {
            showError('email', '邮箱格式不正确');
            isValid = false;
        }
        
        return isValid;
    }
    
    // 显示错误信息
    function showError(field, message) {
        const errorElement = document.getElementById(field + '-error');
        const inputElement = document.querySelector(`[name="${field}"]`);
        
        if (errorElement) {
            errorElement.textContent = message;
            errorElement.style.display = 'block';
        }
        
        if (inputElement) {
            inputElement.classList.add('error');
        }
    }
    
    // 显示多个错误
    function showErrors(errors) {
        for (let field in errors) {
            showError(field, errors[field]);
        }
    }
    
    // 清除错误信息
    function clearErrors() {
        const errorElements = document.querySelectorAll('.form-error');
        const inputElements = document.querySelectorAll('.form-control');
        
        errorElements.forEach(el => {
            el.style.display = 'none';
            el.textContent = '';
        });
        
        inputElements.forEach(el => {
            el.classList.remove('error');
        });
    }
    
    // 实时验证
    document.querySelectorAll('.form-control').forEach(input => {
        input.addEventListener('blur', function() {
            const field = this.name;
            const value = this.value;
            
            // 清除当前字段的错误
            const errorElement = document.getElementById(field + '-error');
            if (errorElement) {
                errorElement.style.display = 'none';
                this.classList.remove('error');
            }
            
            // 实时验证
            if (field === 'username' && value) {
                if (value.length < 3) {
                    showError('username', '用户名至少3个字符');
                } else if (!/^[a-zA-Z0-9_]+$/.test(value)) {
                    showError('username', '用户名只能包含字母、数字和下划线');
                }
            } else if (field === 'password' && value) {
                if (value.length < 6) {
                    showError('password', '密码至少6个字符');
                }
            } else if (field === 'password_confirm' && value) {
                const password = document.querySelector('[name="password"]').value;
                if (value !== password) {
                    showError('password_confirm', '两次输入的密码不一致');
                }
            } else if (field === 'email' && value) {
                if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)) {
                    showError('email', '邮箱格式不正确');
                }
            }
        });
    });
{/block}
